package com.redxun.app.listener;

import com.alibaba.fastjson.JSONArray;
import com.redxun.core.boot.util.FileUtil;
import com.redxun.core.boot.util.WebUtil;
import com.redxun.system.core.service.SysAppServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * 应用初始化.
 * @author zhuweicong
 */
@Component
@Slf4j
public class AppInitStartup implements CommandLineRunner, Ordered {
    
    @Autowired
    SysAppServiceImpl sysAppService;
    
    @Value("${aj.applistPath}")
    private String appListPath;
    
    @Override
    public void run(String... args) throws Exception {
        log.info("==============进行应用安装入口==================");
        log.info("==============安装路径是：" + appListPath + "==================");
        //容器内/home/aj/Release/applist
        File appDir = new File(appListPath);
        if (appDir.exists() && appDir.isDirectory()) {
            File[] appZipFiles = appDir.listFiles();
            for (int i = 0 ; i < appZipFiles.length; i++) {
                File appFile = appZipFiles[i];
                if (!appFile.getName().endsWith("zip")) {
                    continue;
                }
                if (appFile.isFile()) {
                    log.info("正在安装应用:" + appFile.getName());
                    MultipartFile multipartFile = FileUtil.getMultipartFile(appFile);
                    JSONArray array  =  WebUtil.readZipFile(multipartFile);
                    //TODO
                    //sysAppService.install("1","","1009",array);
                    appFile.delete();
                }
            }
        }
    }
    
    @Override
    public int getOrder() {
        return 3;
    }
}
